<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <div class="welcome-text">
          <h1>欢迎回来，{{ userStore.userInfo.username }}！</h1>
          <p>今天是美好的一天，开始您的宿舍生活吧</p>
        </div>
        <div class="welcome-time">
          <div class="time-display">{{ currentTime }}</div>
          <div class="date-display">{{ currentDate }}</div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stats-row">
      <el-col :span="6">
        <div class="stat-card dormitory-card">
          <div class="stat-icon">
            <el-icon><House /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ roomInfo.dormitory || '未选择' }}</div>
            <div class="stat-label">宿舍楼</div>
          </div>
          <div class="stat-bg-icon">
            <el-icon><House /></el-icon>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card room-card">
          <div class="stat-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ roomInfo.roomNum || '未选择' }}</div>
            <div class="stat-label">房间号</div>
          </div>
          <div class="stat-bg-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card bed-card">
          <div class="stat-icon">
            <el-icon><Bed /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ roomInfo.bedNum || '未选择' }}</div>
            <div class="stat-label">床位号</div>
          </div>
          <div class="stat-bg-icon">
            <el-icon><Bed /></el-icon>
          </div>
        </div>
      </el-col>
      
      <el-col :span="6">
        <div class="stat-card order-card">
          <div class="stat-icon">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ unpaidOrders }}</div>
            <div class="stat-label">待支付订单</div>
          </div>
          <div class="stat-bg-icon">
            <el-icon><Money /></el-icon>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="24" class="content-row">
      <!-- 宿舍分布图表 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>宿舍分布统计</span>
              <el-icon><PieChart /></el-icon>
            </div>
          </template>
          <div ref="dormitoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 月度费用趋势 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>月度费用趋势</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <div ref="paymentChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24" class="content-row">
      <!-- 最新公告 -->
      <el-col :span="14">
        <el-card class="announcement-card">
          <template #header>
            <div class="card-header">
              <span>最新公告</span>
              <el-button type="primary" link @click="$router.push('/student/announcements')">
                查看更多 <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </template>
          
          <div class="announcements-list">
            <div 
              v-for="(announcement, index) in recentAnnouncements" 
              :key="announcement.title"
              class="announcement-item"
              @click="showAnnouncementDetail(announcement)"
            >
              <div class="announcement-badge">
                <el-tag :type="announcement.type === '通知' ? 'primary' : 'warning'" size="small">
                  {{ announcement.type }}
                </el-tag>
              </div>
              <div class="announcement-content">
                <div class="announcement-title">{{ announcement.title }}</div>
                <div class="announcement-summary">{{ announcement.content.substring(0, 80) }}...</div>
              </div>
              <div class="announcement-meta">
                <div class="announcement-author">{{ announcement.author }}</div>
                <div class="announcement-time">{{ formatDate(announcement.time) }}</div>
              </div>
            </div>
            
            <div v-if="recentAnnouncements.length === 0" class="empty-state">
              <el-icon><Bell /></el-icon>
              <p>暂无公告</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 快捷操作 -->
      <el-col :span="10">
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
              <el-icon><Operation /></el-icon>
            </div>
          </template>
          
          <div class="quick-actions-grid">
            <div 
              class="action-item select-room"
              @click="$router.push('/student/select-room')"
              :class="{ disabled: !!roomInfo.roomNum }"
            >
              <div class="action-icon">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="action-text">
                <div class="action-title">{{ roomInfo.roomNum ? '已选择宿舍' : '在线选宿' }}</div>
                <div class="action-desc">选择心仪的宿舍</div>
              </div>
            </div>
            
            <div class="action-item payment" @click="$router.push('/student/payment')">
              <div class="action-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="action-text">
                <div class="action-title">费用支付</div>
                <div class="action-desc">查看和支付费用</div>
              </div>
            </div>
            
            <div class="action-item questionnaire" @click="$router.push('/student/questionnaire')">
              <div class="action-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="action-text">
                <div class="action-title">问卷调查</div>
                <div class="action-desc">填写生活习惯</div>
              </div>
            </div>
            
            <div class="action-item repair" @click="$router.push('/student/repair')">
              <div class="action-icon">
                <el-icon><Tools /></el-icon>
              </div>
              <div class="action-text">
                <div class="action-title">宿舍报修</div>
                <div class="action-desc">提交报修申请</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import * as echarts from 'echarts'

const userStore = useUserStore()

const roomInfo = ref({})
const recentAnnouncements = ref([])
const unpaidOrders = ref(0)
const currentTime = ref('')
const currentDate = ref('')

// 图表引用
const dormitoryChartRef = ref()
const paymentChartRef = ref()
let dormitoryChart = null
let paymentChart = null
let timeInterval = null

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

// 初始化宿舍分布图表
const initDormitoryChart = () => {
  if (!dormitoryChartRef.value) return
  
  dormitoryChart = echarts.init(dormitoryChartRef.value)
  
  const option = {
    title: {
      text: '宿舍楼入住情况',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '10',
      left: 'center'
    },
    series: [
      {
        name: '宿舍分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        data: [
          { value: 335, name: '东信一', itemStyle: { color: '#74b9ff' } },
          { value: 310, name: '东信三', itemStyle: { color: '#fd79a8' } },
          { value: 234, name: '西区一', itemStyle: { color: '#fdcb6e' } },
          { value: 135, name: '西区二', itemStyle: { color: '#6c5ce7' } },
          { value: 148, name: '南区', itemStyle: { color: '#a29bfe' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  dormitoryChart.setOption(option)
}

// 初始化费用趋势图表
const initPaymentChart = () => {
  if (!paymentChartRef.value) return
  
  paymentChart = echarts.init(paymentChartRef.value)
  
  const option = {
    title: {
      text: '月度支付统计',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['住宿费', '水电费'],
      bottom: '10'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '住宿费',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          color: '#74b9ff'
        },
        itemStyle: {
          color: '#74b9ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(116, 185, 255, 0.8)'
            }, {
              offset: 1, color: 'rgba(116, 185, 255, 0.1)'
            }]
          }
        },
        data: [1200, 1200, 1200, 1200, 1200, 1200]
      },
      {
        name: '水电费',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          color: '#fd79a8'
        },
        itemStyle: {
          color: '#fd79a8'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(253, 121, 168, 0.8)'
            }, {
              offset: 1, color: 'rgba(253, 121, 168, 0.1)'
            }]
          }
        },
        data: [150, 180, 120, 200, 160, 140]
      }
    ]
  }
  
  paymentChart.setOption(option)
}

// 显示公告详情
const showAnnouncementDetail = (announcement) => {
  // 这里可以添加公告详情弹窗逻辑
  console.log('查看公告详情:', announcement)
}

const loadDashboardData = async () => {
  try {
    // 获取学生信息
    const studentResponse = await request.get('/api/student/profile')
    if (studentResponse.data.code === 200) {
      roomInfo.value = studentResponse.data.data || {}
    }
    
    // 获取最新公告
    const announcementResponse = await request.get('/api/board/list')
    if (announcementResponse.data.code === 200) {
      recentAnnouncements.value = announcementResponse.data.data.slice(0, 3)
    }
    
    // 获取待支付订单数量
    const orderResponse = await request.get('/api/order/my')
    if (orderResponse.data.code === 200) {
      unpaidOrders.value = orderResponse.data.data.filter(order => order.type === '未支付').length
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  if (dormitoryChart) {
    dormitoryChart.resize()
  }
  if (paymentChart) {
    paymentChart.resize()
  }
}

onMounted(async () => {
  // 初始化时间显示
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  
  // 加载数据
  await loadDashboardData()
  
  // 等待DOM渲染完成后初始化图表
  await nextTick()
  initDormitoryChart()
  initPaymentChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理定时器
  if (timeInterval) {
    clearInterval(timeInterval)
  }
  
  // 销毁图表
  if (dormitoryChart) {
    dormitoryChart.dispose()
  }
  if (paymentChart) {
    paymentChart.dispose()
  }
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 60px);
}

/* 欢迎区域 */
.welcome-section {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 24px;
  color: white;
  box-shadow: 0 8px 32px rgba(116, 185, 255, 0.3);
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h1 {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.welcome-text p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.welcome-time {
  text-align: right;
}

.time-display {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 4px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.date-display {
  font-size: 14px;
  opacity: 0.8;
}

/* 统计卡片 */
.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--card-color-start), var(--card-color-end));
}

.dormitory-card {
  --card-color-start: #74b9ff;
  --card-color-end: #0984e3;
}

.room-card {
  --card-color-start: #00b894;
  --card-color-end: #00a085;
}

.bed-card {
  --card-color-start: #fdcb6e;
  --card-color-end: #e17055;
}

.order-card {
  --card-color-start: #fd79a8;
  --card-color-end: #e84393;
}

.stat-icon {
  font-size: 32px;
  color: var(--card-color-start);
  margin-bottom: 16px;
}

.stat-info {
  position: relative;
  z-index: 2;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #2d3436;
  margin-bottom: 4px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #636e72;
  font-weight: 500;
}

.stat-bg-icon {
  position: absolute;
  right: -10px;
  bottom: -10px;
  font-size: 80px;
  color: var(--card-color-start);
  opacity: 0.1;
  transform: rotate(-15deg);
}

/* 内容行 */
.content-row {
  margin-bottom: 24px;
}

/* 图表卡片 */
.chart-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.chart-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 16px 16px 0 0;
}

.chart-container {
  height: 300px;
  width: 100%;
}

/* 公告卡片 */
.announcement-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.announcement-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 16px 16px 0 0;
}

.announcements-list {
  max-height: 400px;
  overflow-y: auto;
}

.announcement-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 12px;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.announcement-item:hover {
  background: #e3f2fd;
  border-color: #74b9ff;
  transform: translateX(4px);
}

.announcement-item:last-child {
  margin-bottom: 0;
}

.announcement-badge {
  margin-right: 12px;
  flex-shrink: 0;
}

.announcement-content {
  flex: 1;
  margin-right: 12px;
}

.announcement-title {
  font-size: 15px;
  font-weight: 600;
  color: #2d3436;
  margin-bottom: 6px;
  line-height: 1.4;
}

.announcement-summary {
  font-size: 13px;
  color: #636e72;
  line-height: 1.4;
}

.announcement-meta {
  text-align: right;
  flex-shrink: 0;
}

.announcement-author {
  font-size: 12px;
  color: #74b9ff;
  font-weight: 500;
  margin-bottom: 4px;
}

.announcement-time {
  font-size: 11px;
  color: #b2bec3;
}

/* 快捷操作卡片 */
.quick-actions-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.quick-actions-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 16px 16px 0 0;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
}

.action-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.6s;
}

.action-item:hover::before {
  left: 100%;
}

.action-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.select-room {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  color: white;
}

.select-room.disabled {
  background: linear-gradient(135deg, #b2bec3, #636e72);
  cursor: not-allowed;
}

.payment {
  background: linear-gradient(135deg, #00b894, #00a085);
  color: white;
}

.questionnaire {
  background: linear-gradient(135deg, #fdcb6e, #e17055);
  color: white;
}

.repair {
  background: linear-gradient(135deg, #fd79a8, #e84393);
  color: white;
}

.action-icon {
  font-size: 28px;
  margin-right: 16px;
  flex-shrink: 0;
}

.action-text {
  flex: 1;
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 13px;
  opacity: 0.9;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2d3436;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  color: #b2bec3;
  padding: 60px 20px;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ddd;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .welcome-time {
    text-align: center;
    margin-top: 20px;
  }
  
  .quick-actions-grid {
    grid-template-columns: 1fr;
  }
  
  .announcement-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .announcement-meta {
    text-align: left;
    margin-top: 8px;
  }
}
</style> 